<template>
  <a-select
    :value="placeholder"
    show-search
    :default-active-first-option="false"
    :show-arrow="true"
    :filter-option="false"
    :not-found-content="null"
    @search="handleSearch"
    @change="handleChange"
    allowClear
  >
    <a-select-option v-for="item in selectOptions" :key="item.value" :value="item.value">
      {{ item.text }}
    </a-select-option>
  </a-select>
</template>
<script lang="ts">
  import { useDebounceFn } from '@vueuse/core';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ref, watch, defineComponent } from 'vue';

  const { createMessage: $message } = useMessage();

  export default defineComponent({
    name: 'JOnlineSearchSelect',
    props: {
      placeholder: {
        type: String,
        default: '',
        required: false,
      },
      value: {
        type: String,
        required: false,
      },
      // online CgReport item id
      fieldId: {
        type: String,
        required: !0,
      },
    },
    emits: ['update:value'],
    setup(props, { emit }) {
      let selected = ref('');
      let selectOptions = ref([]);
      watch(
        () => props.value,
        (newVal) => {
          if (!newVal) {
            selected.value = void 0;
          } else {
            selected.value = newVal;
          }
        },
        { immediate: true }
      );
      watch(
        () => props.fieldId,
        () => {
          resetOptions();
        },
        { immediate: true }
      );
      const handleSearch = useDebounceFn(searchByKeyword, 800);
      function searchByKeyword(keyword = '') {
        let params = {
          keyword,
        };
        let url = '/api-online/online/cgreport/api/getReportDictList?fieldId=' + props.fieldId;
        defHttp.get({ url, params }, { isTransformResponse: false }).then((res) => {
          if (res.success) {
            if (res.data && res.data.length > 0) {
              selectOptions.value = res.data;
            } else {
              selectOptions.value = [];
            }
          } else {
            $message.warning(res.msg);
          }
        });
      }
      function handleChange(value) {
        emit('update:value', value);
        if (!value || value == '') {
          resetOptions();
        }
      }
      function resetOptions() {
        selectOptions.value = [];
        searchByKeyword();
      }
      return {
        selectOptions,
        handleSearch,
        handleChange,
        selected,
      };
    },
  });
</script>
<style scoped></style>
